<?php

namespace App\Http\Controllers;

use App\Models\Sentence;
use Illuminate\Support\Facades\DB;
use Validator;
use Illuminate\Http\Request;

class SentenceController extends Controller
{

  public function index(Request $request)
  {
    $sentences = Sentence::where('title', 'like', '%'. $request->title .'%')
      ->paginate(10)
      ->toArray();
    return $this->success(0, '请求成功', $sentences);
  }

  public function store(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'title' => 'required|between:2,190',
      'content' => 'required|between:2,190',
      'status' => 'required|boolean',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $data = $request->only(['title', 'content', 'status']);
    $sentence = Sentence::create($data);
    return $this->success(0, '添加成功', $sentence);
  }

  public function getOne()
  {
      $sentence = Sentence::where('status', true)
          ->orderBy(DB::raw('rand()'))
          ->first();
      return $this->success(0, 'OK', $sentence);
  }

  /*public function create(Request $request)
  {

  }*/

  public function update(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'id' => 'required|exists:sentences',
      'title' => 'required|between:2,190'
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $data = $request->only(['title', 'content', 'status']);
    $sentence = Sentence::find($request->id);
    $sentence->title = $request->title;
    $sentence->content = $request->input('content');
    $sentence->status = $request->status;
    $sentence->save();
    return $this->success(0, '更新成功！', $sentence);
  }

  public function listpage(Request $request)
  {
    $sentences = Sentence::all();
    return $this->success(0, '请求成功', $sentences);
  }

  public function destroy($id)
  {
    Sentence::destroy($id);
    return $this->success(0, '删除成功！');
  }

  public function batchRemove(Request $request)
  {
    $ids = explode(',', $request->ids);
    foreach ($ids as $id) {
      Sentence::destroy($id);
    }
    return $this->success(0, '删除成功！');
  }

}
